package com.ttdevs.es.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.telephony.TelephonyManager;

import com.ttdevs.util.BaseClass;

public class MainBroadcastManager extends BaseClass {

	public MainBroadcastManager(Context context, Handler handler) {
		super(context, handler);
	}

	public void registerReceiver() {
		if (!getSPU().getUSB() && !getSPU().getHeadSet()) {
			return;
		}

		IntentFilter intentFilter = new IntentFilter();
		if (getSPU().getUSB()) {
			intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
		}
		if (getSPU().getHeadSet()) {
			intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
		}
		intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); // 监听电话

		getContext().registerReceiver(this, intentFilter);
	}

	public void unregisterReceiver() {
		if (!getSPU().getUSB() && !getSPU().getHeadSet()) {
			return;
		}
		getContext().unregisterReceiver(this);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		// 耳机广播的处�?
		if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
			System.out.println(intent.getIntExtra("state", -1));
			if (intent.getIntExtra("state", -1) == 1) {
				// 耳机插入
				getSPU().putHeadsetPlug(true);
			} else {
				// 耳机未插入，若标志为为true则为拔出耳机，触发报�?
				if (getSPU().getHeadsetPlug()) {
					sendAlarmMessage(HEADSET);
				}
				getSPU().putHeadsetPlug(false);
			}
		}

		// USB广播的处�?无需特殊处理，直接报警即�?
		if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {
			sendAlarmMessage(USB);
		}

		// 来电
		if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
			TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);

			switch (tm.getCallState()) {
			case TelephonyManager.CALL_STATE_RINGING:
				sendMessage(STATE_RINGING);
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				System.out.println("TelephonyManager.CALL_STATE_OFFHOOK:" + TelephonyManager.CALL_STATE_OFFHOOK);
				break;
			case TelephonyManager.CALL_STATE_IDLE:
				sendMessage(STATE_IDLE);
				break;
			default:
				break;
			}
		}
	}
}
